package com.eln.medplayer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import android.content.ContentUris;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.provider.MediaStore;

/**
 * Movie list view adapter.
 * 
 * @author Josh
 */
public class MovieListAdaptor extends BaseAdapter
{
	private static final String MEDIA_VIDEO_PATH = new String("/mnt/sdcard/video");
   // public boolean isScrolling=false;
/** Context instance */
private final Context context;

/** Movie list */
private final ArrayList<Movie> movieList;
public static boolean isScrolling=false;


/**
 * Constructor.
 * 
 * @param context context instance.
 * @param movieList movie list.
 */
public MovieListAdaptor(Context context, ArrayList<Movie> movieList)
{
    this.context = context;
    this.movieList = movieList;
}

/**
 * Gets the number of elements in movie list.
 * 
 * @see BaseAdapter#getCount()
 */
public int getCount() {
    return movieList.size();
}

/**
 * Gets the movie item at given position.
 * 
 * @param position item position.
 * @see BaseAdapter#getItem(int)
 */
public Object getItem(int position) {
    return movieList.get(position);
}

/**
 * Gets the movie id at given position.
 * 
 * @param position item position.
 * @return movie id.
 * @see BaseAdapter#getItemId(int)
 */
public long getItemId(int position) {
    return position;
}

/**
 * Gets the item view for given position.
 * 
 * @param position item position.
 * @param convertView existing view to use.
 * @param parent parent view to use.
 */

public static Bitmap drawableToBitmap (Drawable drawable) {
 
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}



public View getView(int position, View convertView, ViewGroup parent) {
    // check if convert view exists or inflate the layout
	//if (!isScrolling){
    if (convertView == null)
    {
    	//convertView = new View(context);
        LayoutInflater layoutInflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = layoutInflater.inflate(R.layout.movie_item, null);
    }

    // Get the movie at given position
    Movie movie = (Movie) getItem(position);

    // Set thumbnail
   //-- ImageView thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
    
    //--TextView title = (TextView) convertView.findViewById(R.id.title_menu);
    //--TextView titleNr = (TextView) convertView.findViewById(R.id.title_nr);

   //-- if (!movie.getMoviePath().contains("mp3"))//((movie.getThumbnailPath() != null) || (movie.getAlbumId() == null))
   //-- {
    	//--String fname=movie.getMoviePath();
    	//--if (!isScrolling )
    	//--{   
    	//==Bitmap scaled = Bitmap.createScaledBitmap(getFrameFromVideo(fname), 256, 150, true);
    	//--thumbnail.setImageBitmap(scaled);
    	//--}
    	
    	//thumbnail.setImageBitmap(ThumbnailUtils.createVideoThumbnail(fname,MediaStore.Images.Thumbnails.MINI_KIND));
       // thumbnail.setImageURI(Uri.parse(movie.getThumbnailPath()));
    //--}
   //-- else// if (movie.getAlbumId() != null)
   //-- {
    	//Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
		//Uri uri = ContentUris.withAppendedId(sArtworkUri, Long.parseLong(movie.getAlbumId()));
		//thumbnail.setImageURI(uri);
	//--	String thpath=movie.getThumbnailPath();
	//--	Uri uri=Uri.parse(thpath);
	/*	try {
			Bitmap bitmap =loadBitmap(thpath);// Images.Media.getBitmap(this.context.getContentResolver() , uri);
			Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 75, 128, true);
			thumbnail.setImageBitmap(scaled);
	//	} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
	//--	if ( !isScrolling )
    //--	{   
    	//
			//Bitmap bitmap=BitmapFactory.decodeFile(thpath);
	//--	  Bitmap bitmap=drawableToBitmap(Drawable.createFromPath(thpath));
	//--	  Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 256, 150, true);	
    //--	  thumbnail.setImageURI(uri);
    //--	}
		//thumbnail.setImageResource(R.drawable.ic_launcher);
    //--}
   // else
    //{
     //   thumbnail.setImageResource(R.drawable.ic_launcher);
    //}
  //--  title.setText(movie.getTitle());//clearedFilename(movie.getTitle()));
 //--   titleNr.setText(getPos(position));
    
    //File vidpath = new File(MEDIA_VIDEO_PATH);
   // String[] vidls=vidpath.list();
    //thumbnail.setImageBitmap(getFrameFromVideo(vidls[0]));
    //title.setText(vidls[0]);
    
    
    // Set title
  //  TextView title = (TextView) convertView.findViewById(R.id.title);
  //  title.setText(movie.getTitle());

    // Set duration
   // TextView duration = (TextView) convertView.findViewById(R.id.duration);
  //  duration.setText(getDurationAsString(movie.getDuration()));
	//}
  /*  ViewHolder holder = new ViewHolder();
    holder.position=position;
    holder.path=movie.getMoviePath();
    holder.thumbpath=movie.getThumbnailPath();
    holder.img=movie.getThumbnail();
   // holder.ll=(ImageView) convertView.findViewById(R.id.thumbnail);
    holder.icon = (ImageView) convertView.findViewById(R.id.thumbnail);
    holder.textNr = (TextView) convertView.findViewById(R.id.title_nr);
    holder.title = (TextView) convertView.findViewById(R.id.title_menu);
    
    holder.textNr.setText(movie.getTitle());//clearedFilename(movie.getTitle()));
    holder.title.setText(getPos(position));
  //  holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);
    convertView.setTag(holder);*/
    
   ImageView thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
   TextView title = (TextView) convertView.findViewById(R.id.title_menu);
   TextView titleNr = (TextView) convertView.findViewById(R.id.title_nr);
   title.setText(movie.getTitle());//clearedFilename(movie.getTitle()));
   titleNr.setText(getPos(position));
   
   ViewHolder holder = new ViewHolder();
   holder.img=movie.getThumbnail();
   holder.icon=thumbnail;
    
    new AsyncTask<ViewHolder, Void, Bitmap>() {
        private ViewHolder v;

        @Override
        protected Bitmap doInBackground(ViewHolder... params) {
            v = params[0];

          /*  Bitmap img =null;
            if (!v.path.contains("mp3"))//((movie.getThumbnailPath() != null) || (movie.getAlbumId() == null))
            {
            	String fname=v.path;
            	img = Bitmap.createScaledBitmap(getFrameFromVideo(fname), 256, 150, true);
            }
            else
            {
        		String thpath=v.thumbpath;
        		Uri uri=Uri.parse(thpath);
         		Bitmap bitmap=drawableToBitmap(Drawable.createFromPath(thpath));
        		img = Bitmap.createScaledBitmap(bitmap, 256, 150, true);	
            }*/
            return v.img;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
           // if (v.position == position) {
                // If this item hasn't been recycled already, hide the
                // progress and set and show the image
               // v.progress.setVisibility(View.GONE);
              //  v.icon.setVisibility(View.VISIBLE);
                v.icon.setImageBitmap(result);
            //}
        }
    }.execute(holder);
    
    return convertView;
}

/*static class ViewHolder {
	  //LinearLayout ll;
	  ImageView icon;
	  TextView textNr;
	  TextView title;
	  ProgressBar progress;
	  int position;
	  String path;
	  String thumbpath;
	  Bitmap img;
	}*/

static class ViewHolder {
	  ImageView icon;
	  Bitmap img;
	}

private static String getPos(int pos){
	String p=Integer.toString(pos+1);
	if (p.length()==1){p="0"+p;}
	return p;
}


private static String getDurationAsString(long duration)
{
    // Calculate milliseconds
    long milliseconds = duration % 1000;
    long seconds = duration / 1000;

    // Calculate seconds
    long minutes = seconds / 60;
    seconds %= 60;

    // Calculate hours and minutes
    long hours = minutes / 60;
    minutes %= 60;

    // Build the duration string
    String durationString = String.format("%1$02d:%2$02d:%3$02d.%4$03d",
            hours, minutes, seconds, milliseconds);

    return durationString;
}

private Bitmap getFrameFromVideo(String name){
	//File sdcard =  new File(MEDIA_VIDEO_PATH);
	//File file = new File(sdcard, name);
	File file = new File(name);
	Bitmap res=null;
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    try {
        retriever.setDataSource(file.getAbsolutePath());

        res=retriever.getFrameAtTime(5000000,MediaMetadataRetriever.OPTION_CLOSEST);


    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
        }
    }
    return res;
}


public String clearedFilename(String filename){
	String res=filename;
  int pos = res.lastIndexOf(".");
  if (pos > -1) res=res.substring(0, pos);
  res=res.replace("_LT","");
  res=res.replace("_EN","");
  pos = res.lastIndexOf("_");
  if (pos > -1) res=res.substring(pos+1, res.length());
	return res;
}

}